package com.huawei.mytestapp.slice;

import com.danikula.videocache.CacheStrategy;
import com.danikula.videocache.Config;
import com.danikula.videocache.HttpProxyCacheServer;
import com.danikula.videocache.ProgressbarView;
import com.danikula.videocache.bean.ProgressBean;
import com.danikula.videocache.defaultStrategy.DefaultCacheStrategy;
import com.danikula.videocache.enums.StrategyType;
import com.danikula.videocache.file.Md5FileNameGenerator;
import com.danikula.videocache.file.TotalCountLruDiskUsage;
import com.danikula.videocache.headers.EmptyHeadersInjector;
import com.danikula.videocache.interfacers.CacheListener;
import com.danikula.videocache.onefileStrategy.OneFileCacheStrategy;
import com.danikula.videocache.slicingStrategy.SlicingCacheStrategy;
import com.danikula.videocache.util.*;
import com.huawei.mytestapp.ResourceTable;
import com.wang.avi.indicators.BallSpinFadeLoaderIndicator;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.components.surfaceprovider.SurfaceProvider;
import ohos.agp.graphics.SurfaceOps;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.CommonDialog;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.Revocable;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.common.Source;
import ohos.media.player.Player;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class CachePlayAbilitySlice extends AbilitySlice implements SurfaceOps.Callback {

    /**
     * 用于datahelper存储选择的策略类型
     */
    public static final String CACHE_STRATEGY = "cache_strategy";
    /**
     * 测试使用的URL
     */
//    public static final String URL = "https://wweb.namibox.com/api/app/video?video=bdb5a2ae4bcdf61d22ae293835708e13" +
//            "&_ts=1536329433";
 //   public static final String URL = "https://1251316161.vod2.myqcloud.com/5f6ddb64vodsh1251316161/6950eead5285890812637029535/iUn2HnRCGxMA.mp4";
    public static final String URL = "http://devimages.apple.com.edgekey.net/streaming/examples/bipbop_4x3/gear4/prog_index.m3u8";
    private String localUrl;
    private Player player;
    private HttpProxyCacheServer mCacheServerProxy = null;
    private Slider slider;
    private SurfaceProvider surfaceProvider;
    private int cacheSlideValue = 0; // 拖动之前的Slider的值
    private long cacheSlideTime = 0; // 拖动之前的时间
    private ProgressbarView progressbarView;
    private boolean isComplete = false;
    private long seekPosition;
    private List<ProgressBean> tempList;
    private CacheStrategy strategy;
    private List<ProgressBean> initSpData;
    private int storeStrategy;
    private Component progressRoot;
    private boolean isRestartFinish = true;
    private boolean isShow = false;
    private Text urlTv;
    private Button btChangeUrl;
    private Revocable revocable;
    private Runnable run;
    private EventHandler handler = new EventHandler(EventRunner.create(true));
    private DirectionalLayout progressContainer;
    private DirectionalLayout rootContainer;


    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_cache_play);
        storeStrategy = getStoreStrategy();
        createStrategy(storeStrategy);
        initServerProxy();
        initDefaultData();
        initView();
        initMediaPlayer();

    }

    @Override
    protected void onActive() {
        super.onActive();
        isShow = true;
        isRestartFinish = true;
        TaskDispatcher globalTaskDispatcher = getGlobalTaskDispatcher(TaskPriority.DEFAULT);
        if (revocable == null) {
            revocable = globalTaskDispatcher.asyncDispatch(new Runnable() {
                @Override
                public void run() {
                    showPrePareData();
                    playee();
                    player.play();
                }
            });
        } else {
            player.play();
        }
    }

    @Override
    protected void onInactive() {
        super.onInactive();
        isShow = false;
        if (player != null) {
            player.pause();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (revocable != null) {
            revocable.revoke();
        }
        if (mCacheServerProxy != null) {
            mCacheServerProxy.shutdown();
            mCacheServerProxy = null;
        }
    }

    /**
     * 获取存储的缓存配置类型
     *
     * @return 存储的缓存配置方案
     */
    private int getStoreStrategy() {
        DatabaseHelper helper = new DatabaseHelper(getContext());
        String name = Config.generateCacheName(URL);
        Preferences preferences = helper.getPreferences(name);
        return preferences.getInt(CACHE_STRATEGY, StrategyType.DEFAULT.getType());
    }

    /***
     * 根据存储的缓存配置类型 生成缓存配置策略
     * @param storeStrategyType 缓存配置类型
     */
    private void createStrategy(int storeStrategyType) {
        if (storeStrategyType == StrategyType.DEFAULT.getType()) {
            strategy = new DefaultCacheStrategy();
        } else if (storeStrategyType == StrategyType.SLICING.getType()) {
            strategy = new SlicingCacheStrategy();
            ((SlicingCacheStrategy) strategy).setMinSingleFileSize(10 * 1024 * 1024);
            ((SlicingCacheStrategy) strategy).setMinFileCacheSize(10 * 1024 * 1024);
        } else if (storeStrategyType == StrategyType.ONEFILE.getType()) {
            strategy = new OneFileCacheStrategy(this);
        } else {
            strategy = new DefaultCacheStrategy(10 * 1024 * 1024);
        }
    }

    private void initServerProxy() {
        if (mCacheServerProxy == null) {
            // 通过Builder创建代理服务对象
            mCacheServerProxy = new HttpProxyCacheServer.Builder(this)
                    .diskUsage(new TotalCountLruDiskUsage(10)) // 设置缓存视频文件的策略为文件数缓存策略
                    .cacheStrategy(strategy) // 设置整体缓存策略
                    .fileNameGenerator(new Md5FileNameGenerator()) // 设置缓存文件重命名规则
                    .cacheDirectory(StorageUtils.getIndividualCacheDirectory(this)) // 设置视频缓存文件的根路径
                    .headerInjector(new EmptyHeadersInjector()) // 添加自定义的头部信息
                    .build();
            mCacheServerProxy.setAttemptsTime(1);
            mCacheServerProxy.setListener(() -> {
                getUITaskDispatcher().asyncDispatch(this::replayIfError);
            });
        }
    }

    private void initDefaultData() {
        tempList = new ArrayList<>();
        for (int j = 0; j <= 100; j++) {
            ProgressBean tempBean = new ProgressBean();
            tempBean.setProgress(j);
            tempBean.setDefault(true);
            tempList.add(tempBean);
        }
    }

    private void initView() {
        urlTv = (Text) findComponentById(ResourceTable.Id_text_play_video);
        urlTv.setText(URL);
        btChangeUrl = (Button) findComponentById(ResourceTable.Id_bt_change_url);
        btChangeUrl.setClickedListener(component -> {
            ToastUtil.showToast(getContext(), getContext().getString(ResourceTable.String_wait_str));
        });
        // 步骤 1 声明布局
        rootContainer = (DirectionalLayout) findComponentById(ResourceTable.Id_play_container);
        // 步骤 2 设置布局大小
        rootContainer.setWidth(ComponentContainer.LayoutConfig.MATCH_PARENT);
        rootContainer.setHeight(ComponentContainer.LayoutConfig.MATCH_PARENT);
        // 步骤 3 设置布局属性及 ID（ID 视需要设置即可）
        rootContainer.setOrientation(Component.VERTICAL);
        rootContainer.setPadding(32, 32, 32, 32);

        initTitleTextAndButton(rootContainer);

        surfaceProvider = new SurfaceProvider(this);
        surfaceProvider.setPadding(10, 80, 10, 80);
        surfaceProvider.setHeight(540);
        surfaceProvider.setWidth(960);
        surfaceProvider.getSurfaceOps().get().addCallback(this);
        surfaceProvider.pinToZTop(true);
        rootContainer.addComponent(surfaceProvider);

        slider = new Slider(this);
        ShapeElement element = new ShapeElement();
        element.setRgbColor(RgbColor.fromArgbInt(Color.LTGRAY.getValue()));
        slider.setProgressBackgroundElement(element);
        slider.setProgressColor(Color.BLUE);
        ShapeElement elementVice = new ShapeElement();
        elementVice.setRgbColor(RgbColor.fromArgbInt(Color.DKGRAY.getValue()));
        slider.setViceProgressElement(elementVice);
        slider.setWidth(960);
        slider.setProgressValue(1);
        rootContainer.addComponent(slider);
        slider.setValueChangedListener(new Slider.ValueChangedListener() {
            @Override
            public void onProgressUpdated(Slider slider, int progress, boolean fromUser) {
                // do nothing
            }

            @Override
            public void onTouchStart(Slider slider) {
                cacheSlideValue = slider.getProgress();
                player.pause();
            }

            @Override
            public void onTouchEnd(Slider slider) {
                player.play();
                if (System.currentTimeMillis() - cacheSlideTime < 1000) {
                    ToastUtil.showToast(getContext(), getContext().getString(ResourceTable.String_prohibited_drag_str));
                    cacheSlideTime = System.currentTimeMillis();
                    slider.setProgressValue(cacheSlideValue);
                    return;
                }
                cacheSlideTime = System.currentTimeMillis();
                seekPosition = player.getDuration() * slider.getProgress() / slider.getMax();
                if (isComplete) {
                    isComplete = false;
                    player.rewindTo(seekPosition * 1000);
                } else {
                    player.rewindTo(seekPosition * 1000);
                }
            }
        });
        /**
         * 段进度条两种加载方式
         * 1.代码加载 initSlicingProgressBar(directionLayout);
         *  2.XML加载 如下：
         */
        initXMLSlicingProgressBar(rootContainer);
        // 加载缓存配置方案选择控件
        initStrategySelectView(rootContainer);
        // 根据当前策略决定是否显示分段进度条
        showOrHideProgress(strategy);
        // 步骤 5 将布局作为根布局添加到视图树中
        addPrepareProgress();
    }

    private void addPrepareProgress() {
        BallSpinFadeLoaderIndicator ballSpinFadeLoaderIndicator1 = new BallSpinFadeLoaderIndicator(this);
        progressContainer = (DirectionalLayout) findComponentById(ResourceTable.Id_progress_container);
        progressContainer.addComponent(ballSpinFadeLoaderIndicator1);
        ballSpinFadeLoaderIndicator1.start();
        run = new Runnable() {
            @Override
            public void run() {
                getUITaskDispatcher().asyncDispatch(new Runnable() {
                    @Override
                    public void run() {
                        if (player.getCurrentTime() > 0) {
                            progressContainer.setVisibility(Component.INVISIBLE);
                            slider.setProgressValue(player.getCurrentTime() * 100 / player.getDuration());
                        }
                        slider.setViceProgress(0);
                    }
                });
                handler.postTask(this, 1000);
            }
        };
        handler.postTask(run, 1000);
    }

    private void initTitleTextAndButton(DirectionalLayout directionLayout) {

        // 步骤 4.1 为控件添加对应布局的布局属性
        DirectionalLayout.LayoutConfig layoutConfig = new
                DirectionalLayout.LayoutConfig(ComponentContainer.LayoutConfig.MATCH_CONTENT,
                ComponentContainer.LayoutConfig.MATCH_CONTENT);
        layoutConfig.alignment = LayoutAlignment.HORIZONTAL_CENTER;

        // 类似的添加一个 Button
        Button button = new Button(this);
        layoutConfig.setMargins(0, 20, 0, 10);
        button.setLayoutConfig(layoutConfig);
        button.setText("播放");
        button.setTextSize(50);
        button.setId(12);
        ShapeElement background = new ShapeElement();
        background.setRgbColor(new RgbColor(0xFF51A8DD));
        background.setCornerRadius(25);
        button.setBackground(background);
        button.setPadding(10, 10, 10, 10);
        button.setClickedListener(new Component.ClickedListener() {
            @Override
            // 在控件中增加对点击事件的监听
            public void onClick(Component Component) {
                if (player == null || player.isNowPlaying()) {
                    return;
                }
                // 按钮被点击 按钮被按下后，需要执行的操作
                player.play();
            }
        });
        directionLayout.addComponent(button);
    }

    private void showOrHideProgress(CacheStrategy strategy) {
        if (strategy instanceof SlicingCacheStrategy
                || strategy instanceof OneFileCacheStrategy) {
            progressRoot.setVisibility(Component.VISIBLE);
        } else {
            progressRoot.setVisibility(Component.HIDE);
        }
    }

    /**
     * 初始化缓存方案选择控件
     *
     * @param directionLayout 方案选择控件的容器
     */
    private void initStrategySelectView(DirectionalLayout directionLayout) {
        Component parse =
                LayoutScatter.getInstance(getContext()).parse(ResourceTable.Layout_layout_config_change_strategy,
                        directionLayout, false);

        RadioContainer rbContainer = (RadioContainer) parse.findComponentById(ResourceTable.Id_rb_container);
        RadioButton rbOneFile = (RadioButton) rbContainer
                .findComponentById(ResourceTable.Id_rb_onefile);
        if (storeStrategy == StrategyType.DEFAULT.getType()) {
            ((RadioButton) rbContainer.findComponentById(ResourceTable.Id_rb_default))
                    .setChecked(true);
        } else if (storeStrategy == StrategyType.SLICING.getType()) {
            ((RadioButton) rbContainer.findComponentById(ResourceTable.Id_rb_slice))
                    .setChecked(true);
        } else if (storeStrategy == StrategyType.ONEFILE.getType()) {
            rbOneFile.setChecked(true);
        } else {
            ((RadioButton) rbContainer.findComponentById(ResourceTable.Id_rb_default))
                    .setChecked(true);
        }
        rbContainer.setMarkChangedListener((radioContainer, checkedId) -> {
            int id = radioContainer.getComponentAt(checkedId).getId();
            clearCurrentStorage();
            switch (id) {
                case ResourceTable.Id_rb_default:
                    restoreStrategyConfig(StrategyType.DEFAULT.getType());
                    break;
                case ResourceTable.Id_rb_slice:
                    restoreStrategyConfig(StrategyType.SLICING.getType());
                    break;
                case ResourceTable.Id_rb_onefile:
                    restoreStrategyConfig(StrategyType.ONEFILE.getType());
                    break;
                default:
                    restoreStrategyConfig(StrategyType.DEFAULT.getType());
                    break;
            }
            restart();

        });
        directionLayout.addComponent(parse);
    }

    /**
     * 因为不同策略使用的缓存的文件的地址都一样
     * 所以切换缓存策略的时候 删除对应的策略自己缓存的临时文件
     * 以免对其他策略的缓存进度的显示产生影响
     */
    private void clearCurrentStorage() {
        if (mCacheServerProxy == null) {
            return;
        }
        mCacheServerProxy.shutdownClients();
        File path = StorageUtils.getIndividualCacheDirectory(getContext());
        File parentFile = path.getParentFile();
        deleteFiles(parentFile);
        File file = mCacheServerProxy.getConfig().generateCacheFile(URL);
        if (file != null && file.exists()) {
            boolean delete = file.delete();
            LogUtil.info(this.getClass().getSimpleName(), "file delete is success :" + delete);
        }
        DatabaseHelper helper = new DatabaseHelper(getContext());
        // 分节点 分片缓存还需要把缓存的信息清空
        if (strategy instanceof OneFileCacheStrategy
                || strategy instanceof SlicingCacheStrategy) {
            Preferences preferences = helper.getPreferences(Config.generateCacheName(URL));
            preferences.clear();
        }
    }

    private void deleteFiles(File parentFile) {
        File[] files = parentFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            if (file.isDirectory()) {
                deleteFiles(file);
            } else {
                boolean delete = file.delete();
                LogUtil.info(this.getClass().getSimpleName(), "file delete is success :" + delete);
            }
        }
    }

    private void restoreStrategyConfig(int strategyType) {
        DatabaseHelper helper = new DatabaseHelper(getContext());
        String name = Config.generateCacheName(URL);
        Preferences preferences = helper.getPreferences(name);
        preferences.putInt(CACHE_STRATEGY, strategyType).flush();
    }

    private void initXMLSlicingProgressBar(DirectionalLayout directionLayout) {
        progressRoot = LayoutScatter.getInstance(getContext()).parse(ResourceTable.Layout_layout_diy_progressbar,
                directionLayout, false);
        progressbarView = (ProgressbarView) progressRoot.findComponentById(ResourceTable.Id_diy_progressbar);
        directionLayout.addComponent(progressRoot);
    }

    /**
     * 使用自定义progressbar显示文件分段存储进度
     * 下载的部分显示为红色
     *
     * @param directionLayout 父容器
     */
    private void initSlicingProgressBar(DirectionalLayout directionLayout) {
        progressbarView = new ProgressbarView(this);
        progressbarView.setmWidth(300);
        progressbarView.setmHeight(10);
        progressbarView.setProgressSegmentColor(Color.RED);
        progressbarView.setCircleX(30);
        progressbarView.setCircleR(20);
        progressbarView.setProBackColor(new Color(ElementUtil.getColor(this, ResourceTable.Color_p_EFEFEF)));
        progressbarView.setProColor(new Color(ElementUtil.getColor(this, ResourceTable.Color_p_EFEFEF)));
        progressbarView.setProgressDoubleSegColor(new Color(ElementUtil.getColor(this, ResourceTable.Color_p_EFEFEF)));
        progressbarView.setmShapeTypeName("square");
        progressbarView.setShowText(false);
        progressbarView.setSquareRadius(8);
        progressbarView.setTextHighColor(new Color(ElementUtil.getColor(this, ResourceTable.Color_p_885500)));
        progressbarView.setTextLowColor(new Color(ElementUtil.getColor(this, ResourceTable.Color_p_880055)));
        progressbarView.setTextMiddleColor(new Color(ElementUtil.getColor(this, ResourceTable.Color_p_008855)));
        progressbarView.setTextSize(13);

        DirectionalLayout.LayoutConfig config = new
                DirectionalLayout.LayoutConfig(ComponentContainer.LayoutConfig.MATCH_CONTENT,
                ComponentContainer.LayoutConfig.MATCH_CONTENT);
        config.setMargins(30, 100, 30, 100);
        config.alignment = LayoutAlignment.HORIZONTAL_CENTER;
        progressbarView.setLayoutConfig(config);
        progressbarView.initWidget(this);
        directionLayout.addComponent(progressbarView);
    }

    private void initMediaPlayer() {
        player = new Player(this);
        player.enableSingleLooping(true);
        player.setPlayerCallback(new Player.IPlayerCallback() {
            @Override
            public void onPrepared() {
                if (seekPosition < 1) {
                    seekPosition = 1;
                }
                player.rewindTo(seekPosition * 1000);
                if (!player.isNowPlaying()) {
                    player.play();
                }
            }

            @Override
            public void onMessage(int type, int extra) {
            }

            @Override
            public void onError(int errorType, int errorCode) {
                getUITaskDispatcher().asyncDispatch(CachePlayAbilitySlice.this::replayIfError);
            }

            @Override
            public void onResolutionChanged(int width, int height) {
            }

            @Override
            public void onPlayBackComplete() {
                isComplete = true;
            }

            @Override
            public void onRewindToComplete() {
            }

            @Override
            public void onBufferingChange(int percent) {
            }

            @Override
            public void onNewTimedMetaData(Player.MediaTimedMetaData mediaTimedMetaData) {
            }

            @Override
            public void onMediaTimeIncontinuity(Player.MediaTimeInfo mediaTimeInfo) {
            }
        });
    }

    private void showPrePareData() {
        if (strategy instanceof OneFileCacheStrategy) {
            initSpData = ((OneFileCacheStrategy) strategy).getInitSpData(ProxyCacheUtils.computeMD5(URL));
        } else if (strategy instanceof SlicingCacheStrategy) {
            initSpData = ((SlicingCacheStrategy) strategy).getInitSpData(getContext(), ProxyCacheUtils.computeMD5(URL));
        } else {
            initSpData = null;
        }
        progressbarView.setProgressList(initSpData);
    }


    /***
     * 如果设置的分节点缓存策略或者分片缓存策略导致无法播放
     * 弹框提示是否转为默认的策略重试
     */
    private void replayIfError() {
        if (!isRestartFinish) {
            return;
        }
        if (!isShow) {
            return;
        }
        isRestartFinish = false;
        if (strategy instanceof SlicingCacheStrategy || strategy instanceof OneFileCacheStrategy) {
            showSelectDialog();
        } else {
            showLoadOriginUrlDialog();
        }

    }

    private void showLoadOriginUrlDialog() {
        CommonDialog dialog = new CommonDialog(getContext());
        Component parse = LayoutScatter.getInstance(getContext()).parse(ResourceTable.Layout_layout_default_strategy,
                null, false);
        parse.findComponentById(ResourceTable.Id_bt_cancle).setClickedListener(component -> {
            dialog.hide();
            dialog.destroy();
        });
        parse.findComponentById(ResourceTable.Id_bt_confirm).setClickedListener(component -> {
            dialog.hide();
            dialog.destroy();
            progressContainer.setVisibility(Component.HIDE);
            rootContainer.removeAllComponents();
            reloadWithOriginUrl();
        });
        dialog.setContentCustomComponent(parse).setCornerRadius(12)
                .setSize(ComponentContainer.LayoutConfig.MATCH_CONTENT, ComponentContainer.LayoutConfig.MATCH_CONTENT)
                .setAlignment(LayoutAlignment.CENTER).show();

    }

    private void reloadWithOriginUrl() {
        initView();
        initMediaPlayer();
        Source source = new Source(URL);
        player.setSource(source);
        player.prepare();
        if (!player.isNowPlaying()) {
            player.play();
        }
    }

    private void showSelectDialog() {
        CommonDialog dialog = new CommonDialog(getContext());
        Component parse = LayoutScatter.getInstance(getContext()).parse(ResourceTable.Layout_layout_change_strategy,
                null, false);
        parse.findComponentById(ResourceTable.Id_bt_cancle).setClickedListener(component -> {
            dialog.hide();
            dialog.destroy();
        });
        parse.findComponentById(ResourceTable.Id_bt_confirm).setClickedListener(component -> {
            clearCurrentStorage();
            restoreStrategyConfig(0);
            restart();
        });
        dialog.setContentCustomComponent(parse).setCornerRadius(12)
                .setSize(ComponentContainer.LayoutConfig.MATCH_CONTENT, ComponentContainer.LayoutConfig.MATCH_CONTENT)
                .setAlignment(LayoutAlignment.CENTER).show();
    }

    private void playee() {
        if (mCacheServerProxy != null && mCacheListener != null) {
            mCacheServerProxy.registerCacheListener(mCacheListener, URL);
        }
        localUrl = mCacheServerProxy.getProxyUrl(URL);
        Source source = new Source(localUrl);
        player.setSource(source);
        player.prepare();
    }

    // 缓存相关
    private CacheListener mCacheListener = new CacheListener() {
        @Override
        public void onCacheAvailable(File cacheFile, String url, int percentsAvailable) {
            slider.setViceProgress(percentsAvailable);
            HiLog.info(new HiLogLabel(3, 0, "cache"), "Saving……,percent:" + String.valueOf(percentsAvailable));
            if (percentsAvailable == 100 && !cacheFile.getPath().endsWith(".download")) {
                HiLog.info(new HiLogLabel(3, 0, "cache"), "Download already!");
            }
        }

        @Override
        public void onCachePartAvailable(File cacheFile, String url, List<long[]> percentsAvailables, long fileLength) {
            /**
             * 显示分段/分节点存储的进度值
             */
            initDefaultData();
            transDataToProgress(percentsAvailables, fileLength);
            progressbarView.setProgressList(tempList);
        }
    };

    private void transDataToProgress(List<long[]> percentsAvailables, long fileLength) {
        for (int i = 0; i < percentsAvailables.size(); i++) {
            long[] longs = percentsAvailables.get(i);
            long start = longs[0];
            long end = longs[1];
            long startProgress = start * 100 / fileLength;
            int startPer = (int) (start * 100 % fileLength == 0 ? startProgress : startProgress + 1);
            long endProgress = end * 100 / fileLength;
            int endPer = (int) (end * 100 % fileLength == 0 ? endProgress : endProgress + 1);
            if (startPer <= 0) {
                startPer = 0;
            }
            if (endPer <= 0) {
                endPer = 0;
            }
            if (endPer > 100) {
                endPer = 100;
            }
            for (int j = 0; j < tempList.size(); j++) {
                if (j >= startPer && j <= endPer) {
                    tempList.get(j).setDefault(false);
                }
            }
        }
    }


    @Override
    public void surfaceCreated(SurfaceOps surfaceOps) {
        player.setSurfaceOps(surfaceProvider.getSurfaceOps().get());
    }

    @Override
    public void surfaceChanged(SurfaceOps surfaceOps, int format, int width, int height) {
        // do nothing
    }

    @Override
    public void surfaceDestroyed(SurfaceOps surfaceOps) {
        // do nothing
    }
}

;

